package com.ytrsoft;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

public class BruteForceTask {

    private final Connectable connect;
    private final List<String> usernameList;
    private final List<String> passwordList;
    private final int blockSize;
    private final AtomicBoolean isSuccess = new AtomicBoolean(false);
    private static final Logger logger = LogManager.getLogger(BruteForceTask.class);

    public BruteForceTask(Connectable connect, int blockSize) {
        this.connect = connect;
        this.usernameList = FileUtils.getUsernameList();
        this.passwordList = FileUtils.getPasswordList();
        this.blockSize = blockSize;
    }

    public void start() {
        int threadCount = (usernameList.size() + blockSize - 1) / blockSize;
        ExecutorService executor = Executors.newFixedThreadPool(threadCount);
        for (int i = 0; i < threadCount; i++) {
            int fromIndex = i * blockSize;
            int toIndex = Math.min((i + 1) * blockSize, usernameList.size());
            List<String> subUsernameList = usernameList.subList(fromIndex, toIndex);
            executor.submit(new RelTask(subUsernameList, passwordList, connect, isSuccess));
        }
        executor.shutdown();
    }

    private static class RelTask implements Runnable {

        private final List<String> usernameList;
        private final List<String> passwordList;
        private final Connectable connect;
        private final AtomicBoolean isSuccess;

        public RelTask(List<String> usernameList, List<String> passwordList, Connectable connect, AtomicBoolean isSuccess) {
            this.usernameList = usernameList;
            this.passwordList = passwordList;
            this.connect = connect;
            this.isSuccess = isSuccess;
        }

        @Override
        public void run() {
            for (String username : usernameList) {
                for (String password : passwordList) {
                    if (isSuccess.get()) {
                        return;
                    }
                    boolean isConnected = connect.isConnected(username, password);
                    if (isConnected) {
                        FileUtils.writeResultFile(username, password);
                        logger.info("成功 username = {} password = {}", username, password);
                        isSuccess.set(true);
                        return;
                    }
                }
            }
        }
    }
}